package com.erpanderp.wam.usm.model.service.projectandassignment;

import java.util.List;

import org.hibernate.FlushMode;
import org.hibernate.Query;
import org.hibernate.Session;

import com.erpanderp.wam.adm.model.entity.Role;
import com.erpanderp.wam.usm.model.entity.projectandassignment.Project;
import com.erpanderp.wam.util.HibernateUtil;


public class ProjectDAO {
	
	public Project createProject(Project project){
		try{
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.getTransaction().begin();
		System.out.println("FLUSH MODE: " + session.getFlushMode());
		session.setFlushMode(FlushMode.COMMIT);
		session.save(project);
		session.getTransaction().commit();
		return project;
		}catch(Exception e){
			e.printStackTrace();
			return null;
		}		
	}
	
	public List<Project> getAllProjects() {
		List<Project> allProjects = null;
		try {
			Session session = HibernateUtil.getSessionFactory().getCurrentSession();
			session.beginTransaction();
			session.setFlushMode(FlushMode.COMMIT);
			Query query = session.createQuery("from Project p where p.status='ACTIVE'");
			query.setCacheable(false);
			allProjects = (List<Project>) query.list();
			session.getTransaction().commit();

		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		return allProjects;
	}
	
	public Project getProjectByProjectID(Long projectId) {
		Project project = null;
		try {
			Session session = HibernateUtil.getSessionFactory()
					.getCurrentSession();
			session.beginTransaction();
			session.setFlushMode(FlushMode.COMMIT);
			String queryString = "from Project p where projectId=:projectId";
			Query query = session.createQuery(queryString).setLong("projectId",projectId);
			query.setCacheable(false);
			project = (Project) query.uniqueResult();
			session.getTransaction().commit();
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		return project;
	}
	
	public Project updateProject(Project project) {
		try {
			Session session = HibernateUtil.getSessionFactory()
					.getCurrentSession();
			session.getTransaction().begin();
			session.setFlushMode(FlushMode.AUTO);
			session.clear();
			session.saveOrUpdate(project);
			session.getTransaction().commit();
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		return project;
	}

}
